﻿Imports System.Web.UI.WebControls
Imports System.Web.UI
Imports DBase.scafolding.Conf
Imports System.Web.UI.HtmlControls
Imports System.Web
Imports DBase.scafolding

Namespace DBase.scafolding

    Public Class CustomControlEdit

        Inherits WebControl
        Implements INamingContainer
        Public Event DataEdit()
        Public Event DataInsert(list As Dictionary(Of String, Object))
        Public Event DataUpdate(list As Dictionary(Of String, Object))
        Public Event DataCanc()
        Public Event DataDelete(list As Dictionary(Of String, Object))
        Dim WithEvents BtnUpdate As New Button
        Dim WithEvents BtnCanc As New Button
        Dim WithEvents pnlform As New Panel

        Public Sub New()
            Me.EnsureChildControls()
            Me.InitControl()
        End Sub

        Private _Config As ConfigTable
        Public Property Config() As ConfigTable
            Get
                Return _Config
            End Get
            Set(ByVal value As ConfigTable)
                _Config = value
               SetConfig()
            End Set
        End Property

        'Private _PK As Dictionary(Of String, Object)
        Public Property PK As Dictionary(Of String, Object)
            Get
                Return ViewState("PK")
            End Get
            Set(ByVal value As Dictionary(Of String, Object))
                ViewState("PK") = value
            End Set
        End Property

        Private _Status As TypeEdit.StatusType
        Public Property Status() As TypeEdit.StatusType
            Get
                Return _Status
            End Get
            Set(ByVal value As TypeEdit.StatusType)
                _Status = value
            End Set
        End Property

        Private Sub InitControl()

            BtnUpdate.Text = "Esegui"
            BtnCanc.Text = "Annulla"
            pnlform.CssClass = "edit_field"
            BtnUpdate.ValidationGroup = "ValidatorGroup_ " & Me.ClientID

        End Sub

        Private Sub SetConfig()

            For Each Field In Me.Config.Fields
                If Field.ShowOutLine Or Field.NotNull Then
                    Dim div_field As New HtmlGenericControl("div")

                    Select Case Field.InputType
                        Case ConfigTable.InputType.[Default]
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim Txt As New TextBox
                            Txt.CssClass = "outline_edit_input"
                            Txt.ID = Field.GetControlName(ConfigTable.InputType.[Default], Field.Name)
                            div_field.Controls.Add(Txt)

                            If Field.ReadOnly Then
                                Txt.Enabled = False
                            End If

                            If Field.Multiline Then
                                Txt.TextMode = TextBoxMode.MultiLine
                                Txt.Rows = Field.Rows
                            End If

                            If Field.NotNull Then
                                Dim Validator As New RequiredFieldValidator
                                Validator.CssClass = "outline_edit_validator"
                                Validator.ForeColor = Drawing.Color.Red
                                Validator.ControlToValidate = Field.GetControlName(ConfigTable.InputType.[Default], Field.Name)
                                Validator.Text = "Inserisci Valore"
                                Validator.ValidationGroup = BtnUpdate.ValidationGroup
                                div_field.Controls.Add(Validator)
                            End If

                            If Field.RegulaExpression Then
                                Dim Validator As New RegularExpressionValidator
                                Validator.CssClass = "outline_edit_regularexpression"
                                Validator.ValidationExpression = RegulaExpression.GetRegulaExpression(Field.RegulaExpression)
                                Validator.ForeColor = Drawing.Color.Red
                                Validator.ControlToValidate = Field.GetControlName(ConfigTable.InputType.[Default], Field.Name)
                                Validator.Text = "Valore Errato"
                                Validator.ValidationGroup = BtnUpdate.ValidationGroup
                                div_field.Controls.Add(Validator)
                            End If

                        Case ConfigTable.InputType.DropDownList
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim Ddl As New DropDownList
                            Ddl.CssClass = "outline_edit_input"
                            Ddl.ID = Field.GetControlName(ConfigTable.InputType.DropDownList, Field.Name)
                            div_field.Controls.Add(Ddl)

                            If Field.NotNull Then
                                Dim Validator As New RequiredFieldValidator
                                Validator.CssClass = "outline_edit_validator"
                                Validator.ForeColor = Drawing.Color.Red
                                Validator.ControlToValidate = Field.GetControlName(ConfigTable.InputType.DropDownList, Field.Name)
                                Validator.Text = "Inserisci Valore"
                                Validator.ValidationGroup = BtnUpdate.ValidationGroup
                                div_field.Controls.Add(Validator)
                            End If

                        Case ConfigTable.InputType.CheckBox
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim Chb As New CheckBox
                            Chb.CssClass = "outline_edit_input"
                            Chb.ID = Field.GetControlName(ConfigTable.InputType.CheckBox, Field.Name)
                            div_field.Controls.Add(Chb)

                        Case ConfigTable.InputType.SearchBox
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim Search As New DBase.scafolding.CustomControlSearch
                            Search.CssClass = "outline_edit_input"
                            Search.ID = Field.GetControlName(ConfigTable.InputType.SearchBox, Field.Name)
                            Search.field = Field
                            div_field.Controls.Add(Search)

                        Case ConfigTable.InputType.SearchView
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim SearchView As New DBase.scafolding.CustomControlView
                            SearchView.CssClass = "outline_edit_input"
                            SearchView.ID = Field.GetControlName(ConfigTable.InputType.SearchView, Field.Name)
                            SearchView.field = Field
                            div_field.Controls.Add(SearchView)

                        Case ConfigTable.InputType.Date
                            Dim lab As New Label
                            lab.CssClass = "outline_edit_label"
                            lab.Text = Field.LabelName
                            div_field.Controls.Add(lab)

                            Dim Calendar As New DBase.scafolding.CustomControData
                            Calendar.CssClass = "outline_edit_input"
                            Calendar.ID = Field.GetControlName(ConfigTable.InputType.Date, Field.Name)
                            div_field.Controls.Add(Calendar)

                    End Select
                    Me.pnlform.Controls.Add(div_field)
                End If
            Next
        End Sub

        Protected Overrides Sub CreateChildControls()
            Controls.Clear()
            Controls.Add(pnlform)
            Controls.Add(New LiteralControl("<br />"))
            Controls.Add(BtnUpdate)
            Controls.Add(BtnCanc)
        End Sub

        Private Sub CustomControlEdit_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            If Not Me.Page.IsPostBack Then
                Bind()
            End If
        End Sub

        Public Sub Bind()

            Dim q = Me.Config.DB.GetQuery
            For Each Field In Me.Config.Fields
                If Field.ShowInLine Or Field.NotNull Then
                    Select Case Field.InputType
                        Case ConfigTable.InputType.DropDownList
                            Dim Ddl = UI.Controls.FindControl(Of DropDownList)(Field.ControlName, Me.pnlform.Controls)
                            Ddl.Items.Clear()
                            Dim DTDdl As DataTable
                            q.Reset()
                            DTDdl = Field.ConfigTable.SqlView.ToDataTable
                            Ddl.Items.Insert(0, New ListItem(Field.SqlFieldDescription, ""))
                            For count = 0 To DTDdl.Rows.Count - 1
                                Ddl.Items.Add(New ListItem(DTDdl.Rows(count)(Field.SqlFieldDescription), DTDdl.Rows(count)(Field.SqlFieldID)))
                            Next
                        Case ConfigTable.InputType.SearchView
                            Dim ViewControl = UI.Controls.FindControl(Of DBase.scafolding.CustomControlView)(Field.ControlName, Me.pnlform.Controls)
                            If PK IsNot Nothing Then
                                ViewControl.filtro = Utils.Conv.ToInt(PK.Values(0))
                            End If
                    End Select
                End If
            Next

            Select Case Me.Status
                Case TypeEdit.StatusType.Update
                    ViewState("Stato") = TypeEdit.StatusType.Update.ToString
                Case TypeEdit.StatusType.Insert
                    ViewState("Stato") = TypeEdit.StatusType.Insert.ToString
                Case TypeEdit.StatusType.Delete
                    ViewState("Stato") = TypeEdit.StatusType.Delete.ToString
            End Select
            InitOutLine()

        End Sub

        Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
            For Each c As Object In Controls
                c.RenderControl(output)
            Next
        End Sub

        Protected Sub BtnUpdate_Click(sender As Object, e As System.EventArgs) Handles BtnUpdate.Click
            EditOutLine([Enum].Parse(GetType(Conf.TypeEdit.StatusType), ViewState("Stato")), Me.Config, e)
        End Sub

        Public Sub EditOutLine(type As Conf.TypeEdit.StatusType, conf As ConfigTable, e As Object)

            Dim q = Me.Config.DB.GetQuery
            Dim p() As Object = Nothing

            Select Case type
                Case TypeEdit.StatusType.Insert
                    q.Insert(Me.Config.Tablename)
                Case TypeEdit.StatusType.Update
                    q.Update(Me.Config.Tablename)
                Case TypeEdit.StatusType.Delete
                    q.Delete(Me.Config.Tablename)
            End Select

            Select Case type
                Case TypeEdit.StatusType.Insert, TypeEdit.StatusType.Update
                    For Each Field In conf.Fields
                        If Field.ShowOutLine Or Field.NotNull Then
                            If Not Field.[ReadOnly] Then
                                Select Case Field.InputType
                                    Case ConfigTable.InputType.[Default]
                                        Dim TxtControl As Object = UI.Controls.FindControl(Of TextBox)(Field.ControlName, Me.pnlform.Controls).Text
                                        p = {Field.Name, DBase.scafolding.Fields.GetConv(Field.FieldType, TxtControl)}
                                    Case ConfigTable.InputType.DropDownList
                                        p = {Field.Name, UI.Controls.FindControl(Of DropDownList)(Field.ControlName, Me.pnlform.Controls).Text}
                                    Case ConfigTable.InputType.CheckBox
                                        p = {Field.Name, UI.Controls.FindControl(Of CheckBox)(Field.ControlName, Me.pnlform.Controls).Checked}
                                    Case ConfigTable.InputType.SearchBox
                                        Dim SrcControl = UI.Controls.FindControl(Of DBase.scafolding.CustomControlSearch)(Field.ControlName, Me.pnlform.Controls)
                                        p = {Field.Name, Utils.Conv.ToInt(SrcControl.Value)}
                                    Case ConfigTable.InputType.Date
                                        Dim DataControl = UI.Controls.FindControl(Of DBase.scafolding.CustomControData)(Field.ControlName, Me.pnlform.Controls).Value
                                        If DataControl <> "" Then
                                            p = {Field.Name, Utils.Conv.ToDate(DataControl)}
                                        Else
                                            p = {Field.Name, Date.Today}
                                        End If
                                End Select
                                Select Case type
                                    Case TypeEdit.StatusType.Insert
                                        q.InsertValues(p)
                                    Case TypeEdit.StatusType.Update
                                        q.UpdateValue(p)
                                End Select
                            End If
                        End If
                    Next
            End Select

            Select Case type
                Case TypeEdit.StatusType.Update, TypeEdit.StatusType.Delete
                    For Each y In Me.PK
                        q.Where(y.Key, "=", y.Value)
                    Next
            End Select

            If conf.Fields.Where(Function(o) o.ReadOnly = False).Count > 0 Then
                q.ExecuteCommand()
            End If

            Select Case type
                Case TypeEdit.StatusType.Insert
                    Dim LastID As Integer = Fields.GetLastID(Me.Config.DB)
                    Dim PK_add As New Dictionary(Of String, Object)
                    PK_add.Add("ID", LastID)
                    RaiseEvent DataInsert(PK_add)
                Case TypeEdit.StatusType.Update
                    RaiseEvent DataUpdate(PK)
                Case TypeEdit.StatusType.Delete
                    RaiseEvent DataDelete(PK)
            End Select

            RaiseEvent DataEdit()

        End Sub

        Public Sub InitOutLine()

            Dim q = Me.Config.DB.GetQuery
            Dim DT As DataTable

            If Me.Config.SqlView IsNot Nothing Then
                q = Me.Config.SqlView.Clone
            Else
                q.Select("*").From(Me.Config.TableName)
            End If

            If Me.Status = TypeEdit.StatusType.Update Or Me.Status = TypeEdit.StatusType.Delete Then
                For Each y In Me.PK
                    q.Where(y.Key, "=", y.Value)
                Next
            End If

            DT = q.ToDataTable()
            If DT.Rows.Count > 0 Then
                Dim DR As DataRow
                DR = DT.Rows(0)
                For Each Field In Me.Config.Fields
                    If Field.ShowOutLine Or Field.NotNull Then
                        Dim c As WebControl = Nothing

                        Select Case Field.InputType
                            Case ConfigTable.InputType.[Default]
                                Dim TxtControl = UI.Controls.FindControl(Of TextBox)(Field.ControlName, Me.pnlform.Controls)
                                c = TxtControl
                                If Me.Status = TypeEdit.StatusType.Insert Then
                                    TxtControl.Text = ""
                                Else
                                    TxtControl.Text = DR(Field.Name).ToString
                                End If

                            Case ConfigTable.InputType.DropDownList
                                Dim Ddl = UI.Controls.FindControl(Of DropDownList)(Field.ControlName, Me.pnlform.Controls)
                                c = Ddl
                                If Me.Status = TypeEdit.StatusType.Insert Then
                                    Ddl.SelectedIndex = 0
                                Else
                                    If Ddl.Items.FindByValue(DR(Field.Name).ToString()) IsNot Nothing Then
                                        Ddl.SelectedValue = DR(Field.Name).ToString()
                                    End If
                                End If

                            Case ConfigTable.InputType.CheckBox
                                Dim CheckBox = UI.Controls.FindControl(Of CheckBox)(Field.ControlName, Me.pnlform.Controls)
                                c = CheckBox
                                If Me.Status = TypeEdit.StatusType.Insert Then
                                    CheckBox.Checked = False
                                Else
                                    CheckBox.Checked = Utils.Conv.ToBool(DR(Field.Name))
                                End If

                            Case ConfigTable.InputType.SearchBox
                                Dim SearchControl = UI.Controls.FindControl(Of DBase.scafolding.CustomControlSearch)(Field.ControlName, Me.pnlform.Controls)
                                c = SearchControl
                                If Me.Status = TypeEdit.StatusType.Insert Then
                                    SearchControl.Value = ""
                                Else
                                    SearchControl.Value = DR(Field.Name)
                                End If

                            Case ConfigTable.InputType.Date
                                Dim DataControl = UI.Controls.FindControl(Of DBase.scafolding.CustomControData)(Field.ControlName, Me.pnlform.Controls)
                                c = DataControl
                                If Me.Status = TypeEdit.StatusType.Insert Then
                                    DataControl.Value = ""
                                Else
                                    DataControl.Value = DR(Field.Name)
                                End If

                        End Select

                        If c IsNot Nothing Then
                            If Me.Status = TypeEdit.StatusType.Delete Or Field.ReadOnly Then
                                c.Enabled = False
                            Else
                                c.Enabled = True
                            End If
                        End If

                    End If
                Next
            End If

        End Sub

        Protected Sub BtnCanc_Click(sender As Object, e As System.EventArgs) Handles BtnCanc.Click
            RaiseEvent DataCanc()
        End Sub
    End Class
End Namespace
